home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10840 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  72 lines

  1. Path: rain.fr!world-net!usenet
  2. From: Frederic LACHASSE <lachass@worldnet.fr>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Can copy constructor and operator= share code?
  5. Date: Fri, 08 Mar 1996 21:39:48 +0000
  6. Organization: World-Net information exchange, Internet provider.
  7. Message-ID: <VA.0000005e.00026e75@fred>
  8. References: <4hinsg$ooq@dekalb.dc.peachnet.edu>
  9. Reply-To: lachass@worldnet.fr
  10. NNTP-Posting-Host: client145.sct.fr
  11. X-Newsreader: Virtual Access by Ashmount Research Ltd, http://www.ashmount.com
  12.  
  13. In article <4hinsg$ooq@dekalb.dc.peachnet.edu>, 
  14. williamh@dekalb.dc.peachnet.edu (darlene williams) wrote:
  15. >
  16. >     i have adopted using a "copy()" member function; the benefit is a single
  17. >     piece of code, and the cost is the probable double-initialization of
  18. >     class members:
  19. >         class foo
  20. >         {
  21. >         public:
  22. >             foo () { }
  23. >             foo &operator = (const foo &rhs) { copy (rhs); return (*this); }
  24. >             foo (const foo &rhs) { copy (rhs); }
  25. >             void copy (const foo &rhs) { b = rhs.b; }
  26. >         private:
  27. >             bar b;
  28. >         };
  29. > >T &T::operator =(const T &t) { ~T(); new(this) T(t); }
  30. >     this is a somewhat interesting approach, but destruction isn't
  31. >     always the same as "resetting" the object to a pre-copy state.
  32. >     i prefer including a "reset()" function whose semantics imply
  33. >     'reset to at-construction state', and not have to worry about
  34. >     any side-effects of destroying the object:
  35. >         T &T::operator = (const T &t) { reset(); copy(t); return(*this); }
  36.  
  37. So what do you do in your destructor? call reset()? If you're doing something 
  38. else, I think there is a problem in your class design.
  39.  
  40. I do not see much differences between writing:
  41.  
  42. class foo
  43. {
  44.   void copy(const foo &f);
  45.   void reset();
  46. public:
  47.   foo(const foo &f) { copy(f); }
  48.   ~foo() { reset(); }
  49.   foo &operator =(const foo &f) { reset(); copy(f); return *this; }
  50. };
  51.  
  52. and:
  53.  
  54. class foo
  55. {
  56. public:
  57.   foo(const foo &);
  58.   ~foo();
  59.   foo &operator =(const foo &f) { ~foo(); new(this) foo(f); return *this; }
  60. };
  61.  
  62. except the important feature allowed by the 2nd formulation: the use of an 
  63. initializer list in the copy constructor.
  64.  
  65.  Frederic LACHASSE (ECP 86)
  66.  CompuServe: 100530,2005
  67.  Internet: lachass@worldnet.fr
  68.  
  69.